/**
 * Created by Ession on 2016/12/16.
 */
var department = {
    events:{
        ".department-body #addDepartment click" : "addDepartment",
        "#editDepartment click" : "addDepartment",
        "#saveDepartment click" : "saveDepartment",
        "#deleteDepartment click" : "deleteDepartment"
    },
    init: function () {
        var _this = this;
        document.title = "部门信息 - 信息管理";
        var temp = Util.template($("#department-template").html(),{});
        $(".commonBody-rightBody").html(temp);
        Util.event.call(_this,_this.events);
        _this.initTree();
        //_this.initCompanyInfo();
        $(".child-department-body").delegate(".childDepartment-block","mousedown", function (e) {
            var $_thisBlock = $(this);
            var $line =$(".insertLine");
            var $departmentBlock = $(".childDepartment-block");
            if($(".childDepartment-block.clone").length>0 || $_thisBlock.hasClass("empty") || $departmentBlock.length<2 || e.button!=0){
                return false;
            }
            var $thisBody = $(".child-department-body");
            var maxTop = $thisBody[0].offsetTop;
            var maxBottom = $thisBody[0].offsetTop+$thisBody.height();
            var maxLeft = $thisBody[0].offsetLeft;
            var amendTop = $_thisBlock.offset().top - e.clientY;
            var c$_thisBlock = $_thisBlock.clone().appendTo(".main").addClass("clone moving").css({
                "position":"absolute",
                "width":$thisBody.innerWidth()-40,
                "background-color":"#E1E2E3",
                "opacity": 0.7
            });
            $(".main").mousemove(function (ee) {
                $_thisBlock.hide(200);
                $line.show();
                var $btn = $("#saveDepartment");
                if(!$btn.hasClass("saveDepartment-show")){
                    $btn.show().addClass("saveDepartment-show").removeClass("saveDepartment-hide")
                }
                var moveTop = ee.clientY+amendTop;
                if(moveTop<maxTop){
                    moveTop = maxTop
                }
                if(moveTop>maxBottom+amendTop){
                    moveTop = maxBottom+amendTop
                }
                c$_thisBlock.css({
                    "top":moveTop,
                    "left":maxLeft
                });
                $departmentBlock.each(function (i) {
                    if(Math.abs(ee.clientY - $($departmentBlock[i]).offset().top) < 19){
                        $departmentBlock[i].before($line[0]);
                        return false;
                    }
                    if(ee.clientY >= maxBottom-40){
                        $departmentBlock[i].after($line[0]);
                    }
                });
            }).mouseup(function (eee) {
                if(eee.clientY != e.clientY && eee.clientX != e.clientX){
                    $_thisBlock.insertAfter(".insertLine");
                    //TODO
                }
                $_thisBlock.show(200);
                $line.hide();
                c$_thisBlock.remove();
                $(this).off("mousemove mouseup");
            })
        })
    },

    settings:{
        _zTree:"",
        _zTreeData:{},
        _zTreeFormatData:{},
        CompanyInfo:{},
        userList:[]
    },
    initTree:function(){
        var _this = this;
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.departmentList(),
            dataType: "json",
            success: function (data) {
                if(data.code==200){
                    $.each(data.result, function (i, n) {
                        n["iconSkin"]= i==0 ?"level01":"level02";
                        n["open"]= i==0
                    });
                    _this.settings._zTreeData = data.result;
                    _this.settings._zTreeFormatData = _this.transformTozTreeFormat(data.result);
                    _this.settings._zTree = $.fn.zTree.init($("#tree"), {
                        //data:{ simpleData: { enable: true}},
                        callback: {
                            onClick: _this._zTree_onClick
                        }
                    }, _this.settings._zTreeFormatData);
                    $("#tree_1_a").trigger("click");

                }
            }
        });
    },
    transformTozTreeFormat: function(sNodes) {
        var _this = this;
        var i,l,
            key = "id",
            parentKey = "pId",
            childKey = "children";
        if (!key || key=="" || !sNodes) return [];
        if (_this.isArray(sNodes)) {
            var r = [];
            var tmpMap = {};
            for (i=0, l=sNodes.length; i<l; i++) {
                tmpMap[sNodes[i][key]] = sNodes[i];
            }
            for (i=0, l=sNodes.length; i<l; i++) {
                if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
                    if (!tmpMap[sNodes[i][parentKey]][childKey])
                        tmpMap[sNodes[i][parentKey]][childKey] = [];
                    tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
                } else {
                    r.push(sNodes[i]);
                }
            }
            return r;
        }else {
            return [sNodes];
        }
    },
    isArray: function(arr) {
        return Object.prototype.toString.apply(arr) === "[object Array]";
    },
    _zTree_onClick: function (event, treeId, treeNode) {
        var _this = department;
        _this.getChildDepartment(treeNode.id);
        _this.initMemberTable(treeNode.id);
        $(".activeDepartment-header").find("span").html(treeNode.name);
        if(Util.isEmpty(treeNode.pId) || treeNode.pId==-1){
            $(".activeDepartment-link").html("<div class='activeLink'><span class=''>"+treeNode.name+"</span><span>&gt;</span></div>");
            $("#editDepartment").hide();
        }else{
            var $last = $(".activeDepartment-link").html(_this.findPNode(treeNode,"<div class='activeLink'><span class='back'>"+treeNode.name+"</span><span>&gt;</span></div>")).find(".activeLink:last-child");
            $last.find("span:nth-child(1)").removeClass("back");
            $last.find("span:nth-child(2)").remove();
            $("#editDepartment").show();
        }
    },
    findPNode: function (node,div) {
        var _this = this;
        $.each(_this.settings._zTreeData, function (i, n) {
            if(node.pId == n.id){
                div="<div class='activeLink'><span class='back'>"+n.name+"</span><span>&gt;</span></div>"+div;
                if(n.pId != -1){
                    div = _this.findPNode(n,div)
                }
                return false;
            }
        });
        return div;
    },
    initCompanyInfo: function (fn) {
        var _this = this;
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.getCompany(),
            dataType: "json",
            success: function (data) {
                if(data.code==200){
                    _this.settings.CompanyInfo = data.result;
                    $.isFunction(fn)?fn(data.result):"";
                }
            }
        });
    },
    initMemberTable: function (id) {
        var _this = this;
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.employeeList(),
            dataType: "json",
            data:{
                id:id
            },
            success: function (data) {
                if(data.code==200){
                    $.each(data.result, function (i, n) {
                        n.g = "<button class='btn btn-default'>编辑</button>";
                    });
                    $(".department-memberTable").cakeTable({
                        head: [
                            {field: "idNum",name: "工号"},
                            {field: "realName",name: "姓名"},
                            {field: "idCard",name: "身份证号码"},
                            {field: "position",name:"职位"},
                            {field: "subPhone",name: "分机号"},
                            {field: "tel",name: "联系电话"},
                            {field: "g",name: "操作",type:2}
                        ],
                        sort: false,
                        columns: data.result,
                        showPage:false,
                        align:"center",
                        rowData:[
                            {key:"id",attrName:"data-id"}
                        ],
                        done: function ($table) {
                            $table.find(".btn-default").click(function (e) {
                                var id = $(this).parents("tr").attr("data-id");
                                Util.ajaxRequest({
                                    type: "get",
                                    url: interfaceURL.getUserInfo(),
                                    dataType: "json",
                                    data: {
                                        id: id
                                    },
                                    success: function (data) {
                                        pop.dialog({
                                            type:"right",
                                            popTitle: "员工信息",
                                            popContent: Util.template($("#employee-info-template").html(), {userInfo:data.result,department:_this.settings._zTreeData}),
                                            onLoad: function () {
                                                /*$("#select").selectBox({
                                                 width:"260px",
                                                 height:"200px",
                                                 attr:[
                                                 {key:"id",attrName:"data-name"}
                                                 ],
                                                 data:[
                                                 {id:1,value:"江苏省",child:[
                                                 {value:"南京"},
                                                 {value:"苏州"},
                                                 {value:"无锡"}
                                                 ]},
                                                 {id:2,value:"浙江省",child:[
                                                 {value:"杭州"},
                                                 {value:"安吉"},
                                                 {value:"宁波"}
                                                 ]},
                                                 {id:3,value:"安徽省",child:[
                                                 {value:"合肥"},
                                                 {value:"滁州"},
                                                 {value:"宿州"}
                                                 ]}
                                                 ]
                                                 })*/
                                            }
                                        }, function () {
                                            var depId = $("#belongDepart").val();
                                            var position = $("#position").val();
                                            var realName = $("#realName").val();
                                            var tel = $("#tel").val();
                                            Util.ajaxRequest({
                                                type: "get",
                                                url: interfaceURL.updateUserInfo(),
                                                dataType: "json",
                                                data: {
                                                    id: id,
                                                    depId: depId,
                                                    position: position,
                                                    realName: realName,
                                                    tel: tel
                                                },
                                                success: function (data) {
                                                    if(data.code==200){
                                                        pop.mAlert("修改成功");
                                                        _this.initMemberTable(_this.settings._zTree.getSelectedNodes()[0].id);
                                                    }
                                                }
                                            })
                                        });
                                    }
                                });
                                e.stopPropagation();
                            })
                        }
                    })
                }
            }
        });

    },
    addDepartment:function (ele,event) {
        var _this = this;
        var type = $(ele).attr("id")=="editDepartment"?"update":"create";
        var pDepartment = _this.settings._zTree.getSelectedNodes()[0];
        console.log({a:pDepartment})
        pop.dialog({
            type:"right",
            popTitle: type=="create"?"添加部门":"修改部门",
            popContent: Util.template($("#department-info-template").html(), {type:type,node:pDepartment,department:_this.settings._zTreeData}),
            onLoad: function () {
                Util.ajaxRequest({
                    type: "get",
                    url: interfaceURL.getUserList(),
                    dataType: "json",
                    data: {
                        currentPage: 1,
                        pageSize: 99999
                    },
                    success: function (data) {
                        if(data.code == 200){
                            var leader = "";
                            $.each(data.result.results, function (i, n) {
                                var select = pDepartment.leader== n.id?"selected='selected'":"";
                                leader+="<option value='"+ n.id+"' "+select+">"+ n.realName+"</option>"
                            });
                            $("#leader").html(leader);
                        }
                    }
                })
            }
        }, function () {
            var departmentName = $("#name").val();
            //departmentName = departmentName==pDepartment.name?"":departmentName;
            var leader = $("#leader").val();
            Util.ajaxRequest({
                type: "get",
                url: type=="create"?interfaceURL.createDepartment():interfaceURL.updateDepartment(),
                dataType: "json",
                data:$.extend({
                    //depNum:new Date().getTime(),
                    //leader:"",
                    name:departmentName,
                    leader:leader
                },type=="create"?{
                    pId:pDepartment.id
                }:{
                    id:pDepartment.id,
                    pId:$("#belongDepart").val()
                }),
                success: function (data) {
                    if(data.code==200){
                        pop.mAlert( type=="create"?"创建成功":"修改成功");
                        _this.initTree();
                    }
                }
            });
        });
        event.stopPropagation();
    },
    getChildDepartment: function (id) {
        var _this = this;
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.getChildDepartment(),
            dataType: "json",
            data:{
                id:id,
                depArr:""
            },
            success: function (data) {
                if(data.code==200){
                    if(id==-1){
                        _this.settings.userList = data.result;
                    }
                    var department = "";
                    $.each(data.result, function (i, n) {
                        department += "<div class='childDepartment-block' data-id='"+ n.id+"'>"+ n.name+"</div>"
                    });
                    if(!Util.isEmpty(department)){
                        $(".child-department-body").html(department).prepend("<div class='insertLine'></div>");
                    }else{
                        $(".child-department-body").html("<div class='insertLine'></div><div class='childDepartment-block empty'>-</div>");
                    }
                }
            }
        });
    },
    saveDepartment: function (ele) {
        var _this = this;
        var a = [];
        $(".childDepartment-block").each(function (i) {
            a.push({
                id:$(this).attr("data-id"),
                new_sort_id:i+1
            })
        });
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.getChildDepartment(),
            dataType: "json",
            data: {
                id: _this.settings._zTree.getSelectedNodes()[0].id,
                depArr:JSON.stringify(a)
            },
            success: function (data) {
                if(data.code == 200){
                    pop.mAlert("排序保存成功");
                    $(ele).addClass("saveDepartment-hide").removeClass("saveDepartment-show").hide(200)
                    _this.initTree();
                }
            }
        })
    },
    deleteDepartment: function () {
        var _this = this;
        var pDepartment = _this.settings._zTree.getSelectedNodes()[0];
        Util.ajaxRequest({
            type: "get",
            url: interfaceURL.deleteDepartment(),
            dataType: "json",
            data: {
                id:pDepartment.id
            },
            success: function (data) {
                if(data.code == 200){
                    pop.mAlert("删除成功");
                    _this.initTree();
                }
            }
        })
    }
};
